import { debounce } from "es-toolkit";

/**
 * 检测用户设备类型
 */
export const detectDevice = (): Device => {
    const ua = navigator.userAgent.toLowerCase();
    const isMobileUA = /mobile|android|iphone|ipad|ipod/i.test(ua);
    const isSmallScreen = window.innerWidth <= 768;
    return isMobileUA || isSmallScreen ? "mobile" : "desktop";
};

/**
 * 监听元素尺寸的变化，内置防抖
 * 参考: https://developer.mozilla.org/zh-CN/docs/Web/API/ResizeObserver
 */
export const watchElementSize = (
    element: HTMLElement,
    callback: (entry: ResizeObserverEntry) => void,
    options?: {
        delay?: number;
        edges?: ("leading" | "trailing")[];
    },
): { unobserve: () => void } => {
    const execute = debounce((entrys: ResizeObserverEntry[]) => callback(entrys[0]), options?.delay || 300, { edges: options?.edges || ["leading", "trailing"] });
    const resizeObserver = new ResizeObserver(execute);
    resizeObserver.observe(element);
    return {
        unobserve: () => {
            resizeObserver.unobserve(element);
        },
    };
};
